var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');

var session = require('express-session');
var bodyParser = require('body-parser');

// region scr
// var ModelIns = require('./model/modelInstance');
var ModelInsCollection = require('./model/modelInsCollection');
var FileUploadRecord = require('./model/fileUpload');
var Global = require('./control/global');
// var init = require('./init');
var settings = require('./setting');
var SysCtrl = require('./control/sysControl');
var Init = require('./control/Integrate/init');

var routes = require('./routes/index');
// endregion

var app = express();

// region scr
global.app = app;
for(let key in Global){
    global[key] = Global[key];
}
//init setting
// init();

app.use(session({
    secret:'wfsiudhjkfhoihiewhrlkjflkjasd',
    cookie:{maxAge : 3600000 * 2},
    resave:false,
    saveUninitialized: true
}));

//正在运行的模型实例集合
app.modelInsColl = new ModelInsCollection();

//创建文件传输记录变量
global.fileupload = new FileUploadRecord();

// endregion

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json({limit:'10000000kb'}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/visualization', express.static(path.join(__dirname, 'visualization_service')));

//http request
routes(app);
// app.use('/', index);
// app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// region scr


//socket connection
// var socket = require('./socket/mc_socket');
// var sockTrans = socket(app);

app.taskInstanceColl = [];
var ip = SysCtrl.getIPSync();
if(ip){
    app.centerHost = SysCtrl.getIPSync();
    app.centerPort = settings.port;
}
//endregion


module.exports = app;
